<template>
  <div>
    <el-dialog
      v-model="visible"
      title="修改地址"
      @before-ok="createOk"
      @close="close(updateRef)"
      width="800px"
      top="100px"
    >
      <div style="width: 400px">
        <el-form
          :model="updateForm"
          ref="updateRef"
          :rules="createRules"
          label-width="120px"
          size="default"
          v-loading="initLoading"
        >
          <el-form-item label="收货人姓名：" prop="name">
            <el-input
              v-model="updateForm.name"
              placeholder="请输入收货人姓名"
            ></el-input>
          </el-form-item>
          <el-form-item label="收货手机号：" prop="phone">
            <el-input
              v-model="updateForm.phone"
              placeholder="请输入收货手机号"
            ></el-input>
          </el-form-item>
          <el-form-item label="收货地区：" prop="region">
            <el-cascader :options="regionList" :props="{
                value:'name',
                label:'name'
            }" clearable v-model="updateForm.region"/>
          </el-form-item>
          <el-form-item label="收货地址：" prop="detail">
            <el-input
              v-model="updateForm.detail"
              placeholder="请输入收货地址"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="flex center">
          <el-button @click="visible = false">取消</el-button>
          <el-button
            type="primary"
            :loading="btnLoading"
            :disabled="btnLoading"
            @click="createOk(updateRef)"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>
    
    
    <script lang="ts">
export default {
  name: "storeOrderUpdateAddress",
};
</script>
    <script lang="ts" setup>
import { ref, getCurrentInstance, nextTick, reactive } from "vue";
import type { FormInstance } from "element-plus";
import type { Result, ResultError } from "@/types";
import { updateOrderAddress, getOrderAddressDetail } from "@/api/store/order";
import { getCascaderRegion } from "@/api/system/region";

const {
  proxy: { $message, $utils },
} = getCurrentInstance() as any;

const emit = defineEmits(["success"]);

const visible = ref<boolean>(false);

const operationId = ref<number>(0);

const updateRef = ref<typeof FormInstance>();

const btnLoading = ref<boolean>(false);

const initLoading = ref<boolean>(true);

const toInit = () => {
  if (!operationId.value) {
    initLoading.value = false;
    return;
  }
  getOrderAddressDetail({ id: operationId.value })
    .then((res: Result) => {
      visible.value = true;
      updateForm.value.name = res.data.name;
      updateForm.value.phone = res.data.phone;
      updateForm.value.detail = res.data.detail;
      updateForm.value.region = [
        res.data.region?.province,
        res.data.region?.city,
        res.data.region?.region,
      ];
      initLoading.value = false;
    })
    .catch((err: ResultError) => {
      $utils.errorMsg(err);
    });
};

const regionList = ref<any>([])

const toInitRegion = () => {
    getCascaderRegion().then((res:Result)=>{
        regionList.value = res.data
    }).catch((err:ResultError)=>{
        $utils.errorMsg(err)
    })
}

const updateForm = ref<any>({
  name: "",
  phone: "",
  detail: "",
  region: [],
});
const createRules: any = reactive({
  name: [{ required: true, message: "收货人姓名不能为空！" }],
  phone: [{ required: true, message: "收货手机号不能为空！" }],
  detail: [{ required: true, message: "详细地址不能为空！" }],
  region: [{ required: true, message: "地区不能为空！" }],
});

const createOk = async (formEl: typeof FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid: any, fields: any) => {
    if (valid) {
      if (btnLoading.value) {
        return;
      }
      btnLoading.value = true;
      updateOrderAddress(
        Object.assign(
          {
            id: operationId.value,
          },
          updateForm.value
        )
      )
        .then((res: Result) => {
          $message.success(res.message);
          close(formEl);
          emit("success");
          btnLoading.value = false;
        })
        .catch((err: ResultError) => {
          $utils.errorMsg(err);
          btnLoading.value = false;
        });
    }
  });
};

const open = (id: number = 0) => {
  initLoading.value = true;
  toInitRegion()
  if (id != 0) {
    operationId.value = id;
  }
  nextTick(() => {
    toInit();
  });
};

const close = async (formEl: typeof FormInstance | undefined) => {
  if (formEl) {
    formEl.resetFields();
  }
  operationId.value = 0;
  visible.value = false;
};

defineExpose({ open });
</script>